package com.haixin.security.service.impl;

import com.haixin.security.bean.User;
import com.haixin.security.dao.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;


/**
 * 登录服务实现类型
 */
@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    UserMapper userMapper;

    @Autowired
    PasswordEncoder passwordEncoder;


    /**
     * 根据用户名查询用户对象和实现列表
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("security 自定义登录服务运行：{}", username);
        User userByName = userMapper.getUserByName(username);
        //1. 查询数据库判断用户名是否存在，如果不存在抛出
        if (userByName == null) {
            log.info("用户不存在");
            throw new UsernameNotFoundException("用户不存在");
        }



        org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
                userByName.getUsername(), userByName.getPassword(), AuthorityUtils.NO_AUTHORITIES
        );
        return user;
    }


}
